<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <!-- 使用双向绑定的方式获取查询的参数 -->
          <el-input v-model="filters.keywords" placeholder="部门名称或者部门编号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="deptQuery" v-perm="'department:list'">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" v-perm="'department:save'">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
<!--
   data: 表单中的数据绑定
   v-loading: 忙等框
   selection-change: 用于表中复选框选择的触发的事件，做批量操作

    -->

<!--
    id	1
    sn	"dept1"
    name	"部门1"
    dirPath	"/1"
    state	1
    manager_id	324
    magager	null
    parent_id	null
    parent	null
    children	[]
   -->
    <el-table :data="Departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>

      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>

      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>



      <el-table-column prop="manager.username" label="部门领导" width="120" sortable>
    </el-table-column>

      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>

<!--      <el-table-column prop="state" label="是否启用" width="100" :formatter="formatSex" sortable>
      </el-table-column>-->
      <el-table-column label="是否启用" width="100">
        <template scope="scope">
          <span style="color: #00ff00" v-if="scope.row.state == 1">启用</span>
          <span style="color: red" v-else-if="scope.row.state == 0">禁用</span>
          <span style="color: gray" v-else>未知</span>
        </template>
      </el-table-column>



      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)" v-perm="'department:update'">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'department:delete'">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--   disabled: 使按钮失效   -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" v-perm="'department:patchDelete'" >批量删除</el-button>
      <el-pagination layout="prev, pager, next"
           @current-change="handleCurrentChange"
           :page-size="pageSize"
           :total="totals"
           style="float: right;">

      </el-pagination>
    </el-col>

    <!--编辑界面
      rules: 表单验证，用于判断用户是否输入数据
      ref： 点击提交按钮时，再次验证是否输入数据 - 为当前模态框取名

    -->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">

      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>


        <el-form-item label="部门状态" prop="state">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="上级部门" prop="parent_id">
        <!--<el-input v-model="editForm.parent_id" auto-complete="off"></el-input>-->

        <!--
              v-model	选中项绑定值
              :options - 可键选项数据源，名可通过 Props 属性配置 []
              :props="{ checkStrictly: true }" 配置选项
                  value	指定选项的值为选项对象的某个属性值，且当value变化时，双向绑定的v-model="editForm.parent_id"
                    中的值也会变化
                  label	指定选项标签为选项对象的某个属性值
                  children	指定选项的子选项为选项对象的某个属性值 此值通过后台发送到前端,即后台的domain对象中含有此children字段
              clearable 是否支持清空选项

              回显机制：
                v-model="editForm.parent_id" 和 value: 'id' 匹配时
        -->
          <el-cascader
              v-model="editForm.parent_id"
              :options="deptTree"
              :props="{ checkStrictly: true, label: 'name', value: 'id'}"
              clearable>


          </el-cascader>


        </el-form-item>

        <el-form-item label="部门经理" prop="manager_id">
          <!--<el-input v-model="editForm.manager" auto-complete="off"></el-input>-->


          <!--

          el-select  下拉框
		      v-model="editForm.manager_id" - 回显数据
		      value-key	作为 value 唯一标识的键名，绑定值为对象类型时必填
		      回显机制：

		      v-model="editForm.manager_id" 与 :value="item.id"对应(v-for中的变量的item中的id)对应
		      如果item中的id与manager_id相同则显示label绑定的item.username
		      注意：v-model=""中的值要与 :value=""中的值类型对应

		      具体例子可以参见官网
          //验证回显的数据绑定
          -->
          <el-select v-model="editForm.manager_id" placeholder="请选择" clearable>

            <!--
                v-for: 循环
                key：一个键值，唯一即可

                label：选择后或初始时匹配到的要显示的数据
                value：向后台发送的数据
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item.id">

              <!--下拉单中显示的内容-->
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>



      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <!--<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addForm.sex">
            <el-radio class="radio" :label="1">男</el-radio>
            <el-radio class="radio" :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
        </el-form-item>
        <el-form-item label="地址">
          <el-input type="textarea" v-model="addForm.addr"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>-->`
  </section>
</template>

<script>

export default {
  data() {

    /**
     * 自定义校验规则
     */
    var validateManager = (rule, value, callback) => {
      if (value === null) {
        callback(new Error('请输入部门经理'));
      } else {

        callback();
      }
    };

    var validateParentDept = (rule, value, callback) => {
      if (value === null) {
        callback(new Error('请输入上级部门'));
      } else {

        callback();
      }
    };

    return {
      deptTree:[],
      employees: [],
      title: "",
      filters: {
        keywords: ''
      },
      Departments: [],
      totals: 0,
      currentPage: 1,
      pageSize: 5,
      listLoading: false,
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        /*state: [
          { required: true, message: '请输入状态', trigger: 'change' }
        ],
        manager_id: [
          { required: true, message: '请输入部门经理', trigger: 'change'}
        ]*/
      },
      //编辑界面数据
      editForm: {
        id: null,
        sn: '',
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null,
      },

    }
  },
  methods: {
    //性别显示转换
    /*formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },*/

    //清除编辑模态框中的回显数据
    clearModal(){

      /**
       * 避免
       * 清空模态框
       */
      this.editForm = {
        id: null,
        sn: '',
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null,
      };

      this.editFormVisible = false;

    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },


    //模态框中部门经理的回显查询
    getEmployees(){
      this.$http.get("/employee")
          .then(res=>{
            this.employees = res.data;
          });

    },

    //模态框中上级部门的数据查询
    getDeptTree(){
      this.$http.get("/department/deptTree")
          .then(res=>{
            this.deptTree = res.data;
          });
    },

    /**
     * 问题：当在非第一页查询时，如果条件查询的结果没有超过一页数据，则会显示空屏，
     * 解决：条件查询配合分页查询，显示第一页的数据
     */
    deptQuery(){
      this.currentPage  = 1;
      this.getDepartments();
    },

    //获取用户列表
    getDepartments() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keywords: this.filters.keywords
      };
      this.listLoading = true;

      /**
       * then(res => {
        //关闭忙等框
        this.listLoading = false;
        this.totals = res.data.totals;
        this.Departments = res.data.data;
      }).catch(res => {
        this.$message.error('后台繁忙，请稍后重试');
      });
       */
      //发送异步请求获取数据
      this.$http.put("/department", para)
          .then(res => {
            //alert("success")
            //关闭忙等框
            this.listLoading = false;
            this.totals = res.data.totals;
            this.Departments = res.data.data;
          }).catch(res => alert("fail!"));
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        //提示框
        type: 'warning'
      }).then(() => {
        //当点击确认时执行

        //忙等框
        this.listLoading = true;

        //获取数据发送请求
        this.$http.delete("/department/" + row.id)
            .then(res => {
                //关闭忙等框
                if(res.data.success){
                  //成功删除
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                }else{
                  //删除失败
                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                }

              //操作完成后，刷新页面
              //当删除完当前页面的最后一条数据后，可以就显示空页面
              //或者每次删除完就重新显示第一页数据
              // this.currentPage = 1;
              this.getDepartments();

            }).catch(res => {
              //发生异常或错误时执行
              this.$message({
                message: '系统异常，稍后重试',
                type: 'error'
          });

        });

        //NProgress.start();
        /*let para = { id: row.id };
        removeDepartment(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepartments();
        });*/
      }).catch(() => {
        //点击取消时执行
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = "编辑";
      //获取模态框中要回显部门经理的数据
      this.getEmployees();


      //获取模态框中要回显部门树的数据
      this.getDeptTree();
      this.editFormVisible = true;

      //通过克隆方式获取回显数据因为数据双向绑定，不能在修改参数时，改变前端显示
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      //修改标题
      this.title = "增加";

      /**
       * 避免
       * 清空模态框
       */
      this.editForm = {
        id: null,
        sn: '',
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null,

      };


      //获取模态框中要回显部门经理的数据
      this.getEmployees();

      //获取模态框中要回显部门树的数据
      this.getDeptTree();

      this.editFormVisible = true;
      console.log(">>>>>",this.editForm)

    },
    //编辑页面的提交按钮的事件绑定函数
    editSubmit: function () {

      //this.$refs.editForm 表单的验证
      this.$refs.editForm.validate((valid) => {
        if (valid) {

          //数据验证成功
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();

            //通过克隆，获取一份数据，因为使用的是双向绑定
            let para = Object.assign({}, this.editForm);

            //提交数据时上级部门数据格式做处理：
            /**
             * 当没有选择时 parent_id 为null
             * 当选择了又清除了 parent_id []
             * 当选择多级部门时，parent_id存储的是一个数组 [],
             * 只需要向后台传递最后一个部门即可
             *
             */
            let arr = para.parent_id;
            if(arr && arr.length==0){//点击清理的时候，是[]
              para.parent_id = null;
            }
            if(arr && arr.length>0){ //[1,13]
              para.parent_id = arr[arr.length-1];
            }

            //发送请求
            this.$http.post("/department", para)
              .then(res => {
                //关闭忙等框
                this.editLoading = false;

                if(res.data.success) {
                  //操作成功
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                }else {
                  //操作失败
                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                }

                //关闭模态框
                this.editFormVisible = false;


                //刷新页面
                this.getDepartments();

              }).catch(res => {
                //发生异常

                //关闭忙等框
                this.editLoading = false;
                this.$message({
                  message: '网络延时，请稍后重试',
                  type: 'error'
                });



                //关闭模态框
                this.editFormVisible = false;

                //刷新页面
                this.getDepartments();
            })


            /*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            editDepartment(para).then((res) => {
              this.editLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['editForm'].resetFields();
              this.editFormVisible = false;
              this.getDepartments();
            });*/

          });
        }
      });

      //清除模态框中的回显数据且关闭模态框
      //this.clearModal();

    },

    //新增
    /*addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);
            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            addDepartment(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getDepartments();
            });
          });
        }
      });
    },*/


    selsChange: function (sels) {
      //复选框选择时将选择的数据记录到data数据模型中的sels中
      this.sels = sels;
      console.log(sels);
    },


    //批量删除
    batchRemove: function () {

      //map 数组的方法映射
      var ids = this.sels.map(item => item.id);


      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        /*let para = { ids: ids };
        batchRemoveDepartment(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepartments();
        });*/

        //发送请求
        this.$http.patch("/department", ids).then((res) => {
          this.listLoading = false;

          if(res.data.success) {
            //success
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }

          //操作成功后刷新页面，可以继续查询当前页的内容,即使当前页的数据被删除完
          this.getDepartments();

        }).catch(res =>{
          //当产生异常时
          this.listLoading = false;
          this.$message({
            message: '网络延迟，请稍后重试！',
            type: 'error'
          });
        });
      }).catch(() => {
        //点击取消按钮
      });
    }
  },
  mounted() {
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>
